/************************************************************************/
/*Copyright (c) James Zhao 2007,2008
/*This file is part of AdminOverlay.
/*AdminOverlay is free software: you can redistribute it and/or modify
/*it under the terms of the GNU General Public License as published by
/*the Free Software Foundation, either version 3 of the License, or
/*(at your option) any later version.
/*
/*AdminOverlay is distributed in the hope that it will be useful,
/*but WITHOUT ANY WARRANTY; without even the implied warranty of
/*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
/*GNU General Public License for more details.
/*
/*You should have received a copy of the GNU General Public License
/*along with Foobar.  If not, see <http://www.gnu.org/licenses/>.                                                                     */
/*************************************************************************/
#include "TextEngine.h"

TextEngine *TextEngine::instance = new TextEngine();

TextEngine::TextEngine()
{
	titleFont = NULL;
	normalFont = NULL;
	canDraw = false;
}

TextEngine::~TextEngine()
{

}

void TextEngine::onDeviceReset()
{
	if(normalFont != NULL)
	{
		normalFont->OnLostDevice();
		normalFont->OnResetDevice();

		titleFont->OnLostDevice();
		titleFont->OnResetDevice();

		fontSprite->OnLostDevice();
		fontSprite->OnResetDevice();
	}	
}

void TextEngine::drawTitleText( QString qs, RECT rect )
{
	if(canDraw)
	{
		LPCTSTR str = qs.utf16();
		titleFont->DrawText(fontSprite, str, -1, &rect, DT_LEFT|DT_NOCLIP,
			0xFFB1B1B1);
	}
}

void TextEngine::drawNormalText( QString qs, RECT rect )
{
	if(canDraw)
	{
		normalFont->DrawText(fontSprite, qs.utf16(), -1, &rect, DT_LEFT|DT_NOCLIP,
			0xFFB1B1B1);
	}
}

void TextEngine::begin()
{
	if(titleFont != NULL && normalFont != NULL && fontSprite != NULL)
	{
		canDraw = true;
		fontSprite->Begin(D3DXSPRITE_ALPHABLEND);
	}
}

void TextEngine::end()
{
	canDraw = false;
	if(fontSprite != NULL)
		fontSprite->End();
}

TextEngine* TextEngine::getInstance()
{
	return instance;
}

void TextEngine::trySetupDevice(LPDIRECT3DDEVICE9 device)
{
	if(titleFont == NULL)
	{
		HRESULT hr = D3DXCreateFont(device, 16, 0, FW_BOLD,1,FALSE, 
			DEFAULT_CHARSET,OUT_DEVICE_PRECIS,
			ANTIALIASED_QUALITY,
			DEFAULT_PITCH|FF_DONTCARE,
			TEXT("Arial"), &titleFont);
	
		hr = D3DXCreateFont(device, 12, 0, FW_NORMAL,1,FALSE, 
			DEFAULT_CHARSET,OUT_DEVICE_PRECIS,
			ANTIALIASED_QUALITY,
			DEFAULT_PITCH|FF_DONTCARE,
			TEXT("Arial"), &normalFont);

		titleFont->PreloadCharacters(32, 127);
		normalFont->PreloadCharacters(32, 127);	

		D3DXCreateSprite(device, &fontSprite);
	}
}